const fs = require('fs');
const path = require('path');
const chalk = require('chalk')
const log = message => console.log(chalk.green(`${message}`))
const successLog = message => console.log(chalk.blue(`${message}`))
const errorLog = error => console.log(chalk.red(`${error}`))
// 获取命令行参数中的子包名称
const packageName = process.argv[2];

// 检查是否提供了子包名称作为命令行参数
if(!packageName) {
    errorLog('请填写子包名称参数 eq: npm run generate packageName');
    process.exit(1);
}

// 定义子包的目录路径
const rootDir = process.cwd();
const packageDir = path.join(rootDir, 'packages', packageName);

if(fs.existsSync(packageDir)) {
    errorLog('该子包已存在，请重新输入子包名称');
    process.exit(1);
}

// 初始化 package.json 的内容
const packageJsonContent = {
    name: `@mysentry/${packageName}`,
    buildOptions: {
        name: `MySentry${packageName.charAt(0).toUpperCase() + packageName.slice(1)}`,
        formats: [
          "esm",
          "cjs"
        ]
      },
    version: '1.0.0',
    description: `${packageName} Package`,
    main: "src/index.ts",
    productionMain: `dist/${packageName}.cjs.js`,
    module: `dist/${packageName}.esm.js`,
    scripts: {
        test: "echo \"Error: no test specified\" && exit 1"
    },
    license: "ISC",
    dependencies: {}
};

const packageJsonString = JSON.stringify(packageJsonContent, null, 2);

// 创建子包目录
fs.mkdirSync(packageDir);
fs.writeFileSync(path.join(packageDir, 'package.json'), packageJsonString)
const srcDir = path.join(packageDir, 'src');
fs.mkdirSync(srcDir);
const indexFile = path.join(srcDir, 'index.ts');
fs.writeFileSync(indexFile, '')
const coreDir = path.join(srcDir, 'core');
fs.mkdirSync(coreDir);
successLog(`子包 ${packageName} 创建成功`);
